// app.js
App({
  globalData: {
    userInfo: null,
    isVip: false,
    theme: 'light',
    adConfig: {
      enabled: true,
      frequency: 0.3, // 广告频率 0-1
      userType: 'new' // new, light, heavy, vip
    }
  },

  onLaunch() {
    console.log('小程序启动');
    this.initApp();
  },

  onShow() {
    console.log('小程序显示');
  },

  onHide() {
    console.log('小程序隐藏');
  },

  // 初始化应用
  initApp() {
    // 检查登录状态
    this.checkLoginStatus();
    
    // 获取系统信息
    this.getSystemInfo();
    
    // 检查更新
    this.checkUpdate();
    
    // 初始化广告配置
    this.initAdConfig();
  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    const isVip = wx.getStorageSync('isVip') || false;
    
    if (userInfo) {
      this.globalData.userInfo = userInfo;
      this.globalData.isVip = isVip;
    }
  },

  // 获取系统信息
  getSystemInfo() {
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.systemInfo = res;
        console.log('系统信息:', res);
      }
    });
  },

  // 检查更新
  checkUpdate() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      
      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(() => {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: (res) => {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              }
            });
          });
        }
      });
    }
  },

  // 初始化广告配置
  initAdConfig() {
    const userInfo = this.globalData.userInfo;
    const adConfig = this.globalData.adConfig;
    
    if (userInfo) {
      // 根据用户行为调整广告频率
      const calculationCount = userInfo.statistics?.totalCalculations || 0;
      
      if (calculationCount < 5) {
        adConfig.userType = 'new';
        adConfig.frequency = 0.1; // 新用户很少广告
      } else if (calculationCount < 20) {
        adConfig.userType = 'light';
        adConfig.frequency = 0.3; // 轻度用户适量广告
      } else {
        adConfig.userType = 'heavy';
        adConfig.frequency = 0.5; // 重度用户较多广告
      }
    }
    
    // VIP用户无广告
    if (this.globalData.isVip) {
      adConfig.enabled = false;
      adConfig.frequency = 0;
    }
  },

  // 用户登录
  login() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            // 获取用户信息
            wx.getUserProfile({
              desc: '用于完善用户资料',
              success: (userRes) => {
                this.handleLoginSuccess(userRes.userInfo, resolve);
              },
              fail: (err) => {
                console.error('获取用户信息失败:', err);
                // 使用默认信息登录
                this.handleLoginSuccess({
                  nickName: '用户',
                  avatarUrl: ''
                }, resolve);
              }
            });
          } else {
            reject(new Error('登录失败'));
          }
        },
        fail: (err) => {
          console.error('微信登录失败:', err);
          reject(err);
        }
      });
    });
  },

  // 处理登录成功
  handleLoginSuccess(userInfo, resolve) {
    const user = {
      id: `user_${Date.now()}`,
      openid: `openid_${Date.now()}`,
      nickname: userInfo.nickName,
      avatar: userInfo.avatarUrl,
      isVip: false,
      statistics: {
        totalCalculations: 0,
        totalAdViews: 0,
        totalAdClicks: 0
      },
      preferences: {
        theme: 'light',
        language: 'zh-CN',
        notifications: true
      },
      createdAt: new Date().toISOString()
    };
    
    // 保存用户信息
    wx.setStorageSync('userInfo', user);
    wx.setStorageSync('isVip', false);
    
    this.globalData.userInfo = user;
    this.globalData.isVip = false;
    
    // 重新初始化广告配置
    this.initAdConfig();
    
    resolve(user);
  },

  // 退出登录
  logout() {
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('isVip');
    
    this.globalData.userInfo = null;
    this.globalData.isVip = false;
    
    // 重新初始化广告配置
    this.initAdConfig();
    
    wx.showToast({
      title: '已退出登录',
      icon: 'success'
    });
  },

  // 显示加载提示
  showLoading(title = '加载中...') {
    wx.showLoading({
      title: title,
      mask: true
    });
  },

  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading();
  },

  // 显示成功提示
  showSuccess(title) {
    wx.showToast({
      title: title,
      icon: 'success'
    });
  },

  // 显示错误提示
  showError(title) {
    wx.showToast({
      title: title,
      icon: 'error'
    });
  },

  // 显示确认对话框
  showConfirm(content, title = '提示') {
    return new Promise((resolve) => {
      wx.showModal({
        title: title,
        content: content,
        success: (res) => {
          resolve(res.confirm);
        }
      });
    });
  },

  // 格式化金额
  formatMoney(amount) {
    return (amount / 10000).toFixed(2) + '万';
  },

  // 格式化利率
  formatRate(rate) {
    return (rate * 100).toFixed(2) + '%';
  },

  // 获取用户类型
  getUserType() {
    const userInfo = this.globalData.userInfo;
    
    if (!userInfo) return 'new';
    if (userInfo.isVip) return 'vip';
    
    const calculationCount = userInfo.statistics?.totalCalculations || 0;
    if (calculationCount < 5) return 'new';
    if (calculationCount < 20) return 'light';
    return 'heavy';
  },

  // 检查是否显示广告
  shouldShowAd() {
    const adConfig = this.globalData.adConfig;
    
    if (!adConfig.enabled) return false;
    
    // 根据频率决定是否显示广告
    return Math.random() < adConfig.frequency;
  }
}); 